package controllers

import (
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"strconv"
	"time"

	"git.oschina.net/Ljohn/softCup/lib"
	"git.oschina.net/Ljohn/softCup/models"
	"git.oschina.net/Ljohn/softCup/sys"
	"golang.org/x/crypto/bcrypt"
	"git.oschina.net/Ljohn/softCup/conf"

	"strings"
	"net/http"
	"errors"
	"encoding/base64"
)

var chanSign = make(chan bool)

func TimeRegisterGitlab() {
	c := time.Tick(time.Second * 5)
	for _ = range c {
		select {
		case <-chanSign:
			return
		default:
			go createUserAndSecretKey()
		}
	}
}

func createUserAndSecretKey() {
	urlPl := conf.MicroServerURL()+ "/manage/api/select_pro_info?pro_status=0&req_token=" + "11qq22e"
	_,testBody, _ ,err:= lib.HttpRequest(urlPl, "GET", nil, nil)
	if err !=nil{
		log.Println("请求发生错误",err)
		go createUserAndSecretKey()
		return
	}

	fmt.Println("-------------------------")
	fmt.Println(string(testBody))

	resTemp := &models.ApiRes{}
	err = json.Unmarshal(testBody, resTemp)
	if err != nil {
		log.Println("获取未注册的用户失败：", err)
		go createUserAndSecretKey()
		return
	}

	//TODO 日志
	for i, v := range resTemp.Data.Pro_info {
		log.Println("第", i, "开始:", time.Now())
		userInfo := "name=" + url.QueryEscape(v.Pro_name) + "&email=" + v.Pro_email + "&password=" + url.QueryEscape(v.Pro_pwd) + "&username=" + v.Pro_username
		userRegURL := conf.GitlabURL()+ "/api/v3/users?private_token=" + conf.TokenAdmin() + "&" + userInfo
		codeStatus,body, head,err:= lib.HttpRequest(userRegURL, "POST", nil, nil)
		if err!=nil{
			fmt.Println(codeStatus)
			log.Println("请求gitlab_API失败",err)
			continue
		}
		if head.Get("Status") != "200 OK" && head.Get("Status") != "201 Created" {
			log.Println("请求Gitlab_API_User失败", string(body))
			continue
		}
		userRes,err := sys.GetUserInfoByEmail(strings.ToLower(v.Pro_email))

		if err != nil {
			log.Println("获取数据失败",err)
			continue
		}
		userModel := &models.GitlabUser{}
		err = json.Unmarshal(userRes, userModel)
		if err != nil {
			log.Println("转换用户JSON失败", err)
			continue
		}


		pri, pub, err := lib.KeyGen("rsa", v.Pro_email, 2048)
		if err != nil {
			log.Println("生成密钥失败：", err)
			continue
		}

		keysURL := conf.GitlabURL()+ "/api/v3/user/keys?id=" + strconv.Itoa(userModel.Id) + "&private_token=" + url.QueryEscape(userModel.Authentication_token) + "&key=" + url.QueryEscape(pub) + "&title=gitclone"

		codeStatus,body, head,err = lib.HttpRequest(keysURL, "POST", nil, nil)
		if err !=nil{
			log.Println("API---请求用户失败",err)
			continue
		}

		if head.Get("Status") != "200 OK" && head.Get("Status") != "201 Created" {
			log.Println("请求GITLAB_API_KEYS 失败:", string(body))
			continue
		}


		err = createRegisterInfo(&v)
		if err != nil {
			log.Println("创建私有仓库账户失败：", err)
			//continue
		}

		updateURL := conf.MicroServerURL()+ "/manage/api/update_pro_info?req_token=" + "11qq22e" + "&email=" + userModel.Email + "&pri_key=" + url.QueryEscape(pri) + "&pub_key=" + url.QueryEscape(pub) + "&pri_token=" + url.QueryEscape(userModel.Authentication_token)
		codeStatus,body, head,err = lib.HttpRequest(updateURL, "POST", nil, nil)
		if err != nil{
			log.Println("请求更新状态失败：",err)
			continue
		}
		res := &models.Result{}
		err = json.Unmarshal(body, res)
		if err != nil {
			log.Println("转换结果JSON失败:", err, "返回信息：", string(body))
			continue
		}
		if res.Code != 200 {
			log.Println("第", i, "个失败", string(body))
			continue
		}
		log.Println("第", i, "个执行成功结束", "~~！")
	}
	return
}

func FixSign() {
	chanSign <- true
}

func createRepertoryInfo(model *models.ApiProInfo) error {
	encryptPwd, err := bcrypt.GenerateFromPassword([]byte(model.Pro_pwd), 0)
	if err != nil {
		return err
	}
	err = sys.SaveRepertoryUserInfo(model.Pro_username, string(encryptPwd), model.Pro_email)
	if err != nil {
		return err
	}
	return nil
}

func createRegisterInfo(model *models.ApiProInfo)error{
	header  :=make(http.Header)
	header.Set("Authorization",conf.Harborbasicauth())
	//registerUrl:="https://106.14.44.62/api/users"

	registerUserUrl:=conf.Harborhost()+"/api/users"


	body := strings.NewReader(`{
		"username":"`+model.Pro_username+`",
		"email": "`+model.Pro_email+`",
		"password": "`+model.Pro_pwd+`",
		"userStatus": 0
	}`)

	codeStatus,res,_,err:= lib.HttpRequest(registerUserUrl,"POST",body,header)
	if err != nil{
		fmt.Println(err)
		return err
	}
	if codeStatus != 201{
		fmt.Println(body)
		return errors.New(string(res))
	}

	strtemp :=model.Pro_username+":"+model.Pro_pwd
	basicAuth := "Basic "+base64.StdEncoding.EncodeToString([]byte(strtemp))
	header.Set("Authorization",basicAuth)

	registerProjectUrl :=conf.Harborhost()+"/api/projects"
	body =strings.NewReader(`{
		"project_name":"`+model.Pro_username+`",
		"public": 0
	}`)
	codeStatus,res,_,err = lib.HttpRequest(registerProjectUrl,"POST",body,header)
	if err != nil{
		return err
	}
	if codeStatus != 201 {
		return errors.New(string(res))
	}
	return nil
}

